/*
 * @Author: 段本显
 * @FilePath: /appiron-i18n-cli/lib/replaceFucn.js
 * @Date: 2022-08-08 17:53:49
 * @LastEditors: 段本显
 * @LastEditTime: 2022-11-25 11:06:43
 * @Email: duanbenxian@appiron.cn
 * 如果有bug，那肯定不是我的锅，噜噜噜
 */
const getCurrentKey = require('./getCurrentKey');

class replaceFucn {
  constructor({
    content,
    file,
    messages,
    messagesHash,
    rootPath,
    config,
    suffix,
  }) {
    this.content = content;
    this.file = file;
    this.messages = messages;
    this.messagesHash = messagesHash;
    this.rootPath = rootPath;
    this.config = config;
    this.suffix = suffix;
  }

  getCurrentHandler(keyText) {
    return getCurrentKey(
      keyText,
      this.file,
      this.messages,
      this.messagesHash,
      this.rootPath,
      this.config
    );
  }

  // 提取国际化json key和value
  getParams(text) {
    let matchIndex = 0;
    let matchArr = [];
    let jsonValue = text.replace(/(\${)([^{}]+)(})/gim, (_, prev, match) => {
      matchArr.push(match);
      return `{${matchIndex++}}`;
    });
    let jsonKey = text.replace(/(\${)([^{}]+)(})/gim, (_, prev, match) => {
      return match;
    });
    jsonValue = jsonValue
      .replace(/(['"`])([\s\S]*)(\1)/, '$2')
      .replace(/(`)([\s\S]*)(\1)/, '$2');
    return { jsonKey, jsonValue, matchArr };
  }

  //中文替换
  replaceChinese(match, sufix, i18nSufix = "'") {
    let result = '';
    let { jsonKey, jsonValue, matchArr } = this.getParams(match);
    const currentKey = this.getCurrentHandler(jsonKey);
    if (!matchArr.length) {
      result = `${sufix}$t(${i18nSufix}${currentKey}${i18nSufix})${
        sufix === 'this.' ? '' : sufix
      }`;
    } else {
      result = `${sufix}$t(${i18nSufix}${currentKey}${i18nSufix}, [${matchArr.toString()}])${
        sufix === 'this.' ? '' : sufix
      }`;
    }
    // 去除jsonValue自带的符号
    this.messages[currentKey] = jsonValue;
    this.messagesHash[jsonValue] = currentKey;
    return result;
  }

  getContent() {
    return this.content;
  }
}

module.exports = replaceFucn;
